package com.sywb.chuangyebao.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.BusinessBean;
import com.sywb.chuangyebao.contract.BusinessDetailsContract;
import com.sywb.chuangyebao.utils.GlideUtils;
import com.sywb.chuangyebao.widget.AutoHeightViewPager;
import com.sywb.chuangyebao.widget.XTabLayout;

import org.bining.footstone.log.Logger;
import org.bining.footstone.rxjava.rxbus.annotation.Subscribe;
import org.bining.footstone.rxjava.rxbus.annotation.Tag;
import org.bining.footstone.rxjava.rxbus.thread.ThreadMode;
import org.bining.footstone.widget.ProgressWebView;
import org.bining.footstone.widget.SlideView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by pxb on 2018/6/13.
 */

public class BusinessDetailsActivity extends ActionbarActivity<BusinessDetailsContract.BusinessDetailsPresenter> implements BusinessDetailsContract.BusinessDetailsView {
    @BindView(R.id.ab1_head)
    AppBarLayout ab1Head;
    @BindView(R.id.tv_toolbar_back)
    ImageView tvToolbarBack;
    @BindView(R.id.rl_toolbar)
    RelativeLayout rlToolbar;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.ctl_head)
    CollapsingToolbarLayout ctlHead;
    @BindView(R.id.tv_toolbar_title)
    TextView tvToolbarTitle;
    @BindView(R.id.ll_add_focus_head)
    RelativeLayout llAddFocusHead;
    @BindView(R.id.business_details_tab)
    XTabLayout businessDetailsTab;
    @BindView(R.id.applet_banner)
    SlideView detailsBanner;
    @BindView(R.id.business_title_tv)
    TextView businessTitleTv;
    @BindView(R.id.recycler_business)
    RecyclerView recyclerBusiness;
    @BindView(R.id.vp_index)
    AutoHeightViewPager vpIndex;
    @BindView(R.id.web_content)
    ProgressWebView webContent;
    @BindView(R.id.cl_index)
    CoordinatorLayout c1Index;
    @BindView(R.id.tv_investment_amount_num)
    TextView tvInvestmentNum;
    @BindView(R.id.tv_viewing_count_num)
    TextView tvViewIngNum;
    @BindView(R.id.tv_favorable_rate_num)
    TextView tvFavorableNum;
    @BindView(R.id.dot_tv)
    TextView dotTv;
    @BindView(R.id.rl_layout)
    RelativeLayout rlLayout;
    @BindView(R.id.stype_tv)
    TextView stypeTv;
    private CollapsingToolbarLayoutState state = CollapsingToolbarLayoutState.EXPANDED;
    private String projectId;

    /**
     * CollapsingToolbarLayout展开、折叠、中间，这三种状态
     */
    private enum CollapsingToolbarLayoutState {
        EXPANDED,// 展开
        COLLAPSED,// 折叠
        INTERNEDIATE// 中间状态
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @SuppressLint("AddJavascriptInterface")
    @Override
    public void initView(Bundle bundle) {
        super.initView(bundle);
        ab1Head.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                Logger.e("verticalOffset:" + verticalOffset + " getTotalScrollRange:" + appBarLayout.getTotalScrollRange());
                if (verticalOffset == 0) {
                    if (state != CollapsingToolbarLayoutState.EXPANDED) {
                        tvToolbarBack.setBackgroundResource(R.drawable.f_back);
                        llAddFocusHead.setBackgroundResource(R.drawable.f_share);
                    }
                    rlToolbar.getBackground().setAlpha(0);
                    state = CollapsingToolbarLayoutState.EXPANDED;//修改状态标记为展开
                } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                    // 设置折叠状态下的界面状态
                    if (state != CollapsingToolbarLayoutState.COLLAPSED) {

                        tvToolbarBack.setBackgroundResource(R.drawable.ic_back_black);
                        llAddFocusHead.setBackgroundResource(R.drawable.news_more_normal);
                        tvToolbarTitle.setVisibility(View.VISIBLE);
                        businessTitleTv.setVisibility(View.GONE);
                        toolbar.setTitle("");
                        ctlHead.setTitle("");
                    }
                    rlToolbar.setBackgroundColor(Color.parseColor("#FFFFFF"));
                    state = CollapsingToolbarLayoutState.COLLAPSED;//修改状态标记为折叠
                } else {

                    float percentage = (float) Math.abs(verticalOffset) / (float) appBarLayout.getTotalScrollRange();
                    if (state == CollapsingToolbarLayoutState.COLLAPSED) {
                        if (percentage <= 0.8) {
                            tvToolbarBack.setBackgroundResource(R.drawable.f_back);
                            llAddFocusHead.setBackgroundResource(R.drawable.f_share);
                            tvToolbarTitle.setVisibility(View.GONE);
                            businessTitleTv.setVisibility(View.VISIBLE);
                        } else {
                            tvToolbarBack.setBackgroundResource(R.drawable.ic_back_black);
                            llAddFocusHead.setBackgroundResource(R.drawable.news_more_normal);
                            tvToolbarTitle.setVisibility(View.VISIBLE);
                            businessTitleTv.setVisibility(View.GONE);
                        }
                    } else {
                        if (percentage >= 0.8) {
                            tvToolbarBack.setBackgroundResource(R.drawable.ic_back_black);
                            llAddFocusHead.setBackgroundResource(R.drawable.news_more_normal);
                            tvToolbarTitle.setVisibility(View.VISIBLE);
                            businessTitleTv.setVisibility(View.GONE);
                        } else {
                            tvToolbarBack.setBackgroundResource(R.drawable.f_back);
                            llAddFocusHead.setBackgroundResource(R.drawable.f_share);
                            tvToolbarTitle.setVisibility(View.GONE);
                            businessTitleTv.setVisibility(View.VISIBLE);
                        }
                    }

                    float alpha = 255 * percentage;
                    if (alpha > 16) {
                        String alphaString = Integer.toHexString((int) alpha);
                        Logger.e("percentage:" + percentage + " alpha:" + alpha + " alphaString:" + alphaString);
                        rlToolbar.setBackgroundColor(Color.parseColor("#" + alphaString + "FFFFFF"));
                    }
                }
            }
        });

        setSupportActionBar(toolbar);
        toolbar.setTitle("");
        ctlHead.setTitle("");
        //使用CollapsingToolbarLayout必须把title设置到CollapsingToolbarLayout上，设置到Toolbar上则不会显示
        //通过CollapsingToolbarLayout修改字体颜色
        ctlHead.setExpandedTitleColor(Color.TRANSPARENT);//设置还没收缩时状态下字体颜色
        ctlHead.setExpandedTitleGravity(Gravity.CENTER);
        ctlHead.setCollapsedTitleTextColor(ContextCompat.getColor(mActivity, R.color.colorDark));//设置收缩后Toolbar上字体的颜色
        ctlHead.setCollapsedTitleGravity(Gravity.CENTER);
        ctlHead.setStatusBarScrimColor(Color.TRANSPARENT);
        rlToolbar.setBackgroundColor(Color.parseColor("#00FFFFFF"));
        initWebView();
        if (getIntent() != null) {
            projectId = getIntent().getStringExtra("p0");
        }
    }

    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.activity_business_details;
    }

    @Override
    public RecyclerView getRecyclerView() {
        return null;
    }


    @Override
    public void initPresenter() {
        mPresenter.initPresenter(this);
    }

    @Override
    public FragmentManager getUserFragmentManager() {
        return getSupportFragmentManager();
    }

    @Override
    public RecyclerView getRecycler() {
        return recyclerBusiness;
    }

    @Override
    public AutoHeightViewPager getViewPager() {
        return vpIndex;
    }

    @Override
    public SlideView getSlideView() {
        return detailsBanner;
    }

    @Override
    public String getPiD() {
        return projectId;
    }

    @Override
    public CoordinatorLayout getC1Index() {
        return c1Index;
    }

    @Override
    public XTabLayout getTabLayout() {
        return businessDetailsTab;
    }

    @Override
    public RelativeLayout getLayoutRl() {
        return rlLayout;
    }

    @Override
    public TextView getLayoutTv() {
        return stypeTv;
    }

    /**
     * 初始化WebView
     */
    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {

        /**
         * setAllowFileAccess 启用或禁止WebView访问文件数据 setBlockNetworkImage 是否显示网络图像
         * setBuiltInZoomControls 设置是否支持缩放 setCacheMode 设置缓冲的模式
         * setDefaultFontSize 设置默认的字体大小 setDefaultTextEncodingName 设置在解码时使用的默认编码
         * setFixedFontFamily 设置固定使用的字体 setJavaSciptEnabled 设置是否支持Javascript
         * setLayoutAlgorithm 设置布局方式 setLightTouchEnabled 设置用鼠标激活被选项
         * setSupportZoom 设置是否支持变焦
         * */
        WebSettings settings = webContent.getSettings();
        settings.setJavaScriptEnabled(true);// 设置支持javascript脚本
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        // 1.NARROW_COLUMNS：可能的话使所有列的宽度不超过屏幕宽度；2.NORMAL：正常显示不做任何渲染；3.SINGLE_COLUMN：把所有内容放大webview等宽的一列中
        // settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);// 排版适应屏幕
        settings.setDisplayZoomControls(false);
        settings.setAllowFileAccess(true); // 启用或禁止WebView访问文件数据
        settings.setBuiltInZoomControls(false); //  隐藏缩放按钮
        settings.setSupportZoom(true); // 支持缩放
        // settings.setUseWideViewPort(true);// 可任意比例缩放
        settings.setLoadWithOverviewMode(true);//setUseWideViewPort方法设置webview推荐使用的窗口；设置webview加载的页面的模式
        settings.setGeolocationEnabled(true);// 启用地理定位
        settings.setDomStorageEnabled(true);
        settings.setSaveFormData(true);// 保存表单数据
        // settings.setSavePassword(true);
        // settings.setTextZoom(200);
        // settings.setMixedContentMode(1);
//         settings.setAcceptThirdPartyCookies();
        settings.setAllowFileAccess(true);
        settings.setAllowContentAccess(true);
        settings.setAllowFileAccessFromFileURLs(true);
        settings.setAllowUniversalAccessFromFileURLs(true);

        webContent.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }
        });

        webContent.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return false;
            }
        });
    }

    @Override
    public void setNoData(boolean isNoData) {

    }

    @OnClick({R.id.tv_toolbar_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_toolbar_back:
                exit();
                break;
        }
    }

    @Override
    public boolean useRxBus() {
        return true;
    }

    @SuppressLint("NewApi")
    @Subscribe(thread = ThreadMode.MAIN_THREAD, tags = {@Tag(Constants.POST_BUSINESS_DETAILS)})
    public void rxBusinessBean(final BusinessBean data) {
        businessTitleTv.setText(data.getProject_name());
        tvInvestmentNum.setText(data.getInvestment());
        tvToolbarTitle.setText(data.getProject_name());
        tvViewIngNum.setText(String.valueOf(data.getCount().getHits()));
        tvFavorableNum.setText(data.getCount().getGood_rate());
        webContent.loadUrl(data.getUrl());
        List<String> images = new ArrayList<>();
        if (data.getImgs() != null && data.getImgs().size() > 0) {
            for (int i = 0; i < data.getImgs().size(); i++) {
                images.add(data.getImgs().get(i));
            }
            detailsBanner.setImageViewsToUrl(images, new SlideView.ImageLoader() {
                @Override
                public void displayImage(Context context, String s, ImageView imageView) {
                    GlideUtils.getNormalIamgeToUrl(mActivity, s, imageView, R.drawable.news_pic_default);
                }
            });
            detailsBanner.invalidate();
        }
        if (data.getImgs() != null) {
            dotTv.setText(1 + "/" + String.valueOf(data.getImgs().size()));
            detailsBanner.getViewPager().addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    if (data.getImgs() != null)
                        dotTv.setText(position + "/" + String.valueOf(data.getImgs().size()));
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
        }
    }
}
